package com.pet_service.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.pet_service.exception.BusinessException;
import com.pet_service.result.ResultCodeEnum;
import com.pet_service.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author 邹全伸
 * @version 1.0
 * @date 2025-10-05 14:51
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 记录所有请求头用于调试
        log.info("Request URL: {}, Method: {}", request.getRequestURL(), request.getMethod());
        // 放行 OPTIONS 预检请求
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            return true;
        }
        // 获取token
        String token = request.getHeader("token");
        log.info("token={}", token);
        if (token == null) {
            //未登陆
            throw new BusinessException(ResultCodeEnum.APP_LOGIN_AUTH);
        } else {
            //验证token
            DecodedJWT decodedJWT = JwtUtil.verifyToken(token, "mySecret", "pet_service");
            if (decodedJWT == null){
                //token失效
                throw new BusinessException(ResultCodeEnum.TOKEN_INVALID);
            }
            //获取顾客手机号码
            String id = JwtUtil.getClaimAsString(token, "mySecret", "pet_service", "id");
            String username = JwtUtil.getClaimAsString(token, "mySecret", "pet_service", "username");
            String phone_number = JwtUtil.getClaimAsString(token, "mySecret", "pet_service", "phone");
            //创建一个包含用户手机号(phone_number)的 LoginUser 对象
            //将该用户对象存储到 LoginUserContext 的线程局部变量(ThreadLocal)中
            //使得在本次请求处理过程中，可以在任意位置通过 LoginUserContext.getLoginUser() 获取到当前登录用户的信息
            LoginUserContext.setLoginUser(new LoginUser(Integer.parseInt(id),username,phone_number));
        }
        // 放行，执行下一个拦截器或处理器
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LoginUserContext.clear();
    }
}
